<template>
	<view class="page-container">
		<view class=" padding-sm">
			<!-- 成员列表 -->
			<view class="padding-tb-xs member-area bg-main  border-radius">
				<view class="dflex-b padding-lr-xs ">
					<view class="dflex margin-left-sm">
						<text class=" ft-dark fs-28 fwbd margin-right-xs">管理员</text>
						<text class="iconfont icon-question-line fs-45 ft-dark-3" @click="messageToggle($event,'info')"
							data-tips='超级管理员: \n 1、可以添加移除管理员，成员；\n 2、可以看到所有事项及合同。'></text>
					</view>
					<view class="padding-tb-xs">
						<template v-if="hasPermissions">
							<view class="padding-tb-xs padding-lr-sm" @click="changeAdmin">
								<text class="fs-23" style="color: #000;">修改</text>
							</view>
						</template>
					</view>
				</view>
				<view class=" dflex padding-tb-xs padding-lr-sm" style="flex-wrap: wrap;">
					<view class="admin padding-tb-sm padding-lr-sm border-radius-sm dflex-fs"
						v-for="(item,idx) in superAdmin" style="min-width: 230px;">
						<view class="headimg pos-r" style="width: 57.5px;height: 57.5px;">
							<image :src="item.avatarUrl" class=" border-radius avatar"></image>
						</view>
						<view class="padding-left-sm dflex-b flex1">
							<view>
								<text class="clamp tac fs-26 padding-tb-xs">{{item.nickName}}</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 操作权限控制 -->
		<view class="padding-lr">
			<view class="dflex-b margin-left-sm">
				<view>
				</view>
				<view class="share-box dflex">
					<view class="dflex padding-sm">
						<view class="headimg big border-radius-sm dflex-c border-dashed2 margin-right-lg"
							@click="addMember('添加老师信息','server')">
							<text class="tac fs-25 fwbd" style="line-height: 1.25;">添加<br>
								老师信息</text>
						</view>
						<!-- #ifdef H5 -->
						<view class="headimg big border-radius-sm dflex-c" @click="addMember('添加老师信息','server')"
							style="color: #07c160;background-color: #2583c1;">
							<text class="clamp-2 tac fs-25 padding-tb-xs ft-white wpre-65" style="line-height: 1.5;">微 信邀
								请</text>
						</view>
						<!-- #endif -->
						<!-- #ifdef MP-WEIXIN || APP||H5 -->
						<button class="headimg big dflex-c  padding-tb-xxs no-border  use-hover bg-base border-radius-sm"
							style="color: #07c160;background-color: #2583c1;" open-type="share">
							<text class="clamp-2 tac fs-25 padding-tb-xs ft-white" style="line-height: 1.5;">微 信邀 请</text>
						</button>
						<!-- #endif -->
					</view>
				</view>

			</view>
		</view>

		<view class=" padding-sm">
			<view class="bg-main border-radius" style="display: none;">
				<!-- 搜索内容区 -->
				<view class="search-area pos-r w-full dflex-b padding-lr-sm padding-tb-xs">
					<view class="dflex-c flex1 bg-gray-2 border-radius-big padding-lr-sm pos-r">
						<view class="icon-search pos-a" style="left: 15px;">
							<uni-icons type="search" size="21" />
						</view>
						<input type="text" class="padding-left w-full padding-tb-xs  box-sizing-b" maxlength="20"
							style="border-top-right-radius: 0;border-bottom-right-radius: 0;"
							:placeholder="searchItem.placeholder" @confirm="onSearchConfirm"
							v-model="searchItem.searchTxt" />
					</view>
					<view class="padding-tb-16 tac" @click="searchHandle" style="width: 45px;">
						<text style="color: #00abe0;">搜索</text>
					</view>
				</view>
			</view>
			<view class="dflex-e" style="display: none;">
				<view class="padding-tb-xs" style="width: 135px;">
					<uni-segmented-control :current="current" :values="sortList"
						@clickItem="checkCurrent($event,'state')" styleType="button">
					</uni-segmented-control>
				</view>
			</view>
			<view style="height: 10rpx;"></view>
			<!-- 成员列表 -->
			<view class="padding-tb-xs bg-main border-radius member-area">
				<view class="padding-bottom-sm dflex-b padding-lr-xs padding-top-xs">
					<view class="dflex margin-left-sm">
						<text class=" ft-dark fs-28 fwbd margin-right-xs">家庭成员</text>
						<text class="iconfont icon-question-line fs-45 ft-dark-3" @click="messageToggle($event,'info')"
							data-tips='管理员:\n 1、可以看到所有事项及合同；\n 2、可以邀请成员。'></text>
					</view>
					<view class="padding-tb-xs" style="width: 135px;">
					</view>
				</view>
				
				<view class=" dflex padding-tb-xs padding-lr-sm" style="flex-wrap: wrap;">
					<view class="item " v-for="(item,index) in memberList" :key="index"
						@click="checkMember('admin',item,index)" :class="{'checked':item.checked}">
						<template v-if="item.rid!='625'">
							<view class="margin-lr-sm padding-tb-xs">
								<view class="headimg pos-r">
									<template v-if="showAdminRemove">
										<template v-if="!item.isSuperAdmin">
											<view class="pos-a wh-full" @click.stop="delAdminMember(item,index)"
												style="z-index:92;">
												<uni-icons class="tag pos-a right top" type="minus" color="#f30000"
													size="22" />
											</view>
										</template>
									</template>
									<uni-icons class="tag pos-a right bottom check" type="checkmarkempty"
										color="#f50000" size="22" style="line-height: 1;" />
									<image :src="item.avatarUrl" class=" border-radius-lg avatar"></image>
									<template v-if="item.rid=='625'">
										<image src="@/static/icons/icon-admin-02.png" class="tag pos-a"></image>
									</template>
									<template v-if="item.rid=='626'">
										<image src="@/static/icons/icon-admin-01.png" class="tag pos-a"></image>
									</template>
								</view>
								<text class="clamp tac fs-20 padding-tb-xs">{{item.nickName}}</text>
							</view>
						</template>
					</view>
					<!-- 操作权限 -->
					<template v-if="hasPermissions">
						<view class="item margin-lr-sm padding-tb-xs" @click="addAdminMember()">
							<view class="headimg pos-r tac border-radius-sm border-dashed" style="line-height: 1.25;">
								<!-- <uni-icons :size="32" class="uni-icon-wrapper" color="#bbb" type="plusempty" /> -->
								<text class="iconfont icon-tianjia fs-45 fwbd" style="line-height: 45px;"></text>
							</view>
							<text class="clamp tac fs-20 padding-tb-xs">添加</text>
						</view>
						<view class="item margin-lr-sm padding-tb-xs" @click="removeMember('admin')">
							<view class="headimg pos-r tac border-radius-sm border-dashed" style="line-height: 1.25;">
								<!-- <uni-icons :size="32" class="uni-icon-wrapper" color="#bbb" type="minus" /> -->
								<text class="iconfont icon-jianshao fs-45 fwbd" style="line-height: 45px;"></text>
							</view>
							<text class="clamp tac fs-20 padding-tb-xs">移出</text>
						</view>
					</template>
				</view>
			</view>

			<view style="height: 15rpx;"></view>
			<view class="padding-tb-xs bg-main border-radius member-area">
				<view class="padding-tb-sm dflex-b padding-lr-xs">
					<view class="dflex margin-left-sm">
						<text class=" ft-dark fs-28 fwbd margin-right-xs">老师</text>
						<text class="iconfont icon-question-line fs-45 ft-dark-3" @click="messageToggle($event,'info')"
							data-tips='成员:\n  1、只能看到和自己相关的事项及合同；\n 2、可以邀请成员。'></text>
					</view>
				</view>
				<view class="dflex padding-sm">
					<view class="headimg big border-radius-sm dflex-c border-dashed2 margin-right-lg"
						@click="addMember('添加老师信息','server')">
						<text class="tac fs-25 fwbd" style="line-height: 1.25;">添加<br>
							老师信息</text>
					</view>
					<!-- #ifdef H5 -->
					<view class="headimg big border-radius-sm dflex-c" @click="addMember('添加老师信息','server')"
						style="color: #07c160;background-color: #2583c1;">
						<text class="clamp-2 tac fs-25 padding-tb-xs ft-white wpre-65" style="line-height: 1.5;">微 信邀
							请</text>
					</view>
					<!-- #endif -->
					<!-- #ifdef MP-WEIXIN || APP||H5 -->
					<button class="headimg big dflex-c  padding-tb-xxs no-border  use-hover bg-base border-radius-sm"
						style="color: #07c160;background-color: #2583c1;" open-type="share">
						<text class="clamp-2 tac fs-25 padding-tb-xs ft-white" style="line-height: 1.5;">微 信邀 请</text>
					</button>
					<!-- #endif -->
				</view>
				<view class=" dflex padding-tb-xs padding-lr-sm" style="flex-wrap: wrap;">
					<view class="item margin-lr-sm padding-tb-xs tac" v-for="(item,index) in teacherList" :key="index"
						@click="checkMember('member',item,index)" :class="{'checked':item.checked||item.already}">
						<view class="headimg pos-r" style="margin: 0 auto;">
							<template v-if="showRemove">
								<template v-if="!item.isSuperAdmin">
									<view class="pos-a wh-full" @click.stop="delMember(item,index)" style="z-index:92;">
										<uni-icons class="tag pos-a right top" type="minus" color="#f30000" size="22" />
									</view>
								</template>
							</template>
							<!-- <uni-icons class="tag pos-a right bottom check" v-if="item.already" type="checkmarkempty" color="#74f57f" size="22"
							style="line-height: 1;" /> -->
							<uni-icons class="tag pos-a right bottom check" v-if=" item.checked" type="checkmarkempty"
								color="#f50000" size="22" style="line-height: 1;" />
							<view class="tag pos-a center border-radius-big dflex-c" v-if="item.locking"
								style="background-color: rgba(0, 0, 0, 0.35);width: 100%;height: 100%;">
								<text class="iconfont icon-42 fs-50" style="color: #ececec;"></text>
							</view>
							<image :src="item.avatarUrl" class=" border-radius-lg avatar" @error="handleImageError"
								alt="Image"></image>
							<template v-if="item.rid=='625'">
								<image src="@/static/icons/icon-admin-02.png" class="tag pos-a"></image>
							</template>
							<template v-if="item.rid=='626'">
								<image src="@/static/icons/icon-admin-01.png" class="tag pos-a"></image>
							</template>
						</view>
						<text class="clamp tac fs-20 padding-tb-xs"
							style="max-width: 52.5px;">{{item.nickName||'微信用户'}}</text>
					</view>
					<!-- 操作权限控制 -->
					<template v-if="hasPermissions">
						<!-- #ifdef MP-WEIXIN || APP -->
						<view class="item margin-lr-sm padding-tb-xs" style="display: none;">
							<button class="dflex-c dflex-flow-c no-border  use-hover"
								style="color: #07c160;background-color: transparent;" open-type="share">
								<view class="headimg pos-r tac border-radius-sm border-dashed"
									style="line-height: 1.25;">
									<!-- <uni-icons :size="32" class="uni-icon-wrapper" color="#bbb" type="plusempty" /> -->
									<text class="iconfont icon-zengjia"></text>
								</view>
								<text class="clamp tac fs-20 padding-tb-xs" style="line-height: 1;">邀请</text>
							</button>
						</view>
						<!-- #endif -->
						<!-- #ifdef H5 -->
						<view class="item margin-lr-sm padding-tb-xs" @click="InviteMember()" style="display: none;">
							<view class="headimg pos-r tac border-radius-sm border-dashed" style="line-height: 1.25;">
								<!-- <uni-icons :size="32" class="uni-icon-wrapper" color="#bbb" type="plusempty" /> -->
								<text class="iconfont icon-tianjia fs-45 fwbd" style="line-height: 45px;"></text>
							</view>
							<text class="clamp tac fs-20 padding-tb-xs">添加</text>
						</view>
						<!-- #endif -->
						<view class="item margin-lr-sm padding-tb-xs" @click="removeMember('membar')">
							<view class="headimg pos-r tac border-radius-sm border-dashed" style="line-height: 1.25;">
								<!-- <uni-icons :size="32" class="uni-icon-wrapper" color="#bbb" type="minus" /> -->
								<text class="iconfont icon-jianshao fs-45 fwbd" style="line-height: 45px;"></text>
							</view>
							<text class="clamp tac fs-20 padding-tb-xs">移出</text>
						</view>
					</template>
				</view>
				<template v-if="memberList.length == 0">
					<use-empty tip="暂无数据" btnTip="" height="25vh" />
				</template>
			</view>
			<view style="height: 15rpx;"></view></view>
		<template v-if="source=='1'">
			<view class="w-full safe-area-inset-bottom" style="height: 120rpx;"></view>
			<!-- 底部操作栏  -->
			<view class="oper-area pos-f pos-b-full w-full dflex-b bg-main safe-area-inset-bottom ">
				<view class="dflex padding-lr-sm">
					<text class="fs-25">
						共选择({{totalNum}})个联系人
					</text>
				</view>
				<view class="padding-lr-sm">
					<view class="submit dflex-c border-radius-big padding-lr animated-all"
						:class="isubmit ? 'use-loading' : 'bg-base'" @click="toSubmit">
						{{ !isubmit ? '完成' : '' }}
					</view>
				</view>
			</view>
		</template>
		<!-- 负责人/参与成员选择，单选、多选 -->
		<use-popup mode="bottom" bgclass=" " :zIndex='99' close-icon :show="showMemberPicker" type="member"
			@open='openPopup' @close="closePopup('member')">
			<view class="bg-main border-radius-top30 safe-area-inset-bottom">
				<view class="pos-a pos-top pos-right padding-sm" @click="closePopup('member')">
					<uni-icons type="closeempty" size="21" color="#626262" />
				</view>
				<view class="tac  w-full padding-lr fwb padding-top padding-bottom ">
					<text class="fs-30">组织成员</text>
				</view>
				<view class="padding-sm">
					<view class="seach-area">
						<view class="search-box">
							<uni-easyinput class="uni-mt-5 " suffixIcon="search" v-model="searchValue" placeholder="搜索"
								@focus='searchFocus' @blur="onSearchClick">
							</uni-easyinput>
						</view>
					</view>
				</view>
				<view style="height: 25rpx;"></view>

				<scroll-view scroll-y="true" class="scroll-Y" style="max-height: 65vh;min-height: 45vh;">
					<view class="checkbox dflex" style="flex-wrap: wrap;">
						<use-member-item v-for="(item, index) in memberList" :key="index"
							@check="checkTeamMember(item,index)" :item="item" :index="index">
						</use-member-item>
					</view>
				</scroll-view>
				<!-- <view class="checkbox pos-r" style="min-height: 65vh; max-height: 85vh;">
					<uni-indexed-list :options="allMemberList" :show-select="true" @click="bindClick" />
				</view> -->
				<view class="dflex-c padding-tb-sm">
					<view class="btn wpre-65 border-radius-lg" @click="checkUserOver">
						<text>完成</text>
					</view>
				</view>
			</view>
		</use-popup>

		<!-- 提示信息弹窗 -->
		<uni-popup ref="message" type="message">
			<uni-popup-message :type="msgType" :message="messageText" :duration="2000"></uni-popup-message>
		</uni-popup>
	</view>
</template>

<script setup>
	// import pinyin from 'pinyin'; // --按首字母排序
	// --组合式 API 模板
	import {
		ref,
		inject,
		onMounted,
		computed,
		getCurrentInstance,
		defineEmits
	} from 'vue'
	import {
		storeToRefs
	} from 'pinia';

	import {
		useRouter,
		useRoute
	} from 'vue-router';
	import {
		useUserStore
	} from '@/store'
	import {
		onLoad,
		onShow,
		onShareAppMessage,
		onShareTimeline
	} from "@dcloudio/uni-app";

	const {
		ctx,
		proxy
	} = getCurrentInstance();
	console.log("ctx", ctx);

	const value = inject('message', '这是默认值')
	console.log(value)
	let UserStore = useUserStore()
	const title = ref("标题")
	const source = ref(0)
	const hasPermissions = ref(false)
	const Disabled = ref(false)
	const isubmit = ref(0)
	const sortList = ref(['成员身份', '首字母'])
	const current = ref(0)
	const updateType = ref('admin')
	const superAdmin = ref({});
	// --成员列表
	const showMemberPicker = ref(false)
	const showAdminRemove = ref(false)
	const showRemove = ref(false)
	const lockingId = ref('')
	const teacherList = ref([])
	const allMemberList = ref([])
	const memberList = ref([])
	const checkedList = ref([])
	const NonStaffList = ref([]); // --外部人员
	const groupedData = ref([])
	const state = ref('')
	const empty = ref(false)
	const modeType = ref('checkbox')
	const searchItem = ref({
		placeholder: '',
		searchTxt: ''
	})
	const memberType=ref("family");// --family,--server
	const memberId=ref("");
	const memberItem=ref("");
	// --成员列表搜索项
	const searchFocus = ref(false)
	const searchValue = ref('')

	const msgType = ref('info')
	const messageText = ref('');
	// onLoad 接受 A 页面传递的参数
	onLoad((option) => {
		console.log("B 页面 onLoad:", option); //B 页面 onLoad: {id: '1', name: 'uniapp'}
		modeType.value = option.type;
		if (option && option.creater) {
			lockingId.value = option.creater;
		}

		if (option && option.id) {
			checkedList.value = option.id.split(',');
		}

		if (option && option.source) {
			source.value = option.source || 0;
			Disabled.value = option.source == 0 ? true : false;
		}
		//   --设置标题
		uni.setNavigationBarTitle({
			title: option.title || '组织成员'
		});
		onLoadData();
		permissions();
	});
	onShow(() => {
		console.log("B 页面 onShow");

	});
	const scroll = function() {}
	const onSearchConfirm = function() {}
	const searchHandle = function() {
		if (!searchItem.value.searchTxt) {
			proxy.$utils.msg("请输入查询关键词")
			return;
		}

	}
	// 确认选择
	const toSubmit = () => {
		// -排序，管理员放第一个
		let members = []
		memberList.value.forEach((x) => {
			if (x.checked) {
				members.push(JSON.parse(JSON.stringify(x)))
			}
		})
		NonStaffList.value.forEach((x) => {
			if (x.checked) {
				members.push(JSON.parse(JSON.stringify(x)))
			}
		})
		members = members.sort((a, b) => b.isSuperAdmin - a.isSuperAdmin);
		console.log(members);
		if (source.value == 1) {
			uni.$emit('__event_choice_member', members);
			uni.navigateBack();
		}
	}
	const checkMember = (mode, item, idx) => {
		console.log(mode, item, modeType.value, idx)
		if (Disabled.value) return;
		if (item.locking) return; // --人员锁定
		switch (mode) {
			case 'admin':

				break;
			case 'member':
				switch (modeType.value) {
					case 'radio':
						memberList.value.forEach((x, i) => {
							if (idx == i) {
								memberList.value[idx].checked = !memberList.value[idx].checked;
							} else {
								memberList.value[i].checked = false;
							}
						})

						break;
					case 'checkbox':
						memberList.value[idx].checked = !memberList.value[idx].checked;
						break;
					default:
				}
				break;
			case 'NonStaff':
				if (modeType.value == 'radio') return;
				NonStaffList.value[idx].checked = !NonStaffList.value[idx].checked;
				break;
			default:
		}
		console.log(memberList.value)
	}
	const handleImageError = (event) => {
		console.log(event)
		event.target.src = './../static/images/custom-error-image.jpg';
	}
	const addAdminMember = () => {
		modeType.value = "radio";
		showMemberPicker.value = true;
		showAdminRemove.value = false;
	}
	const removeMember = (type) => {
		switch (type) {
			case 'admin':
				showAdminRemove.value = !showAdminRemove.value;
				break;
			case 'membar':
				showRemove.value = !showRemove.value;
				break;
			default:
				break;
		}
	}

	const delAdminMember = (item, idx) => {
		console.log(item, idx);
		if (item.isSuperAdmin) return;
		let _name = item.nickName || '匿名用户';
		proxy.$utils.alert('您确定要移除‘' + _name + '’的管理员权限吗？', function(bool) {
			if (bool) {
				let _mode = {
					ids: item._id,
					inherit: '',
					type: '0'
				}
				console.log(_mode)
				loadData('P_Saas_UserAuthOpera', _mode, (res) => {
					console.log(res)
					try {
						if (res && res.status == '1') {
							proxy.$utils.msg(res.data1[0].tips);
							// --删除后更新成员数据
							proxy.$utils.timerout(() => {
								showAdminRemove.value = false;
								onLoadData();
							}, 350)
							return;
						}
						proxy.$utils.msg("系统错误");
					} catch (e) {
						//TODO handle the exception
					}
				});
			}
		}, false);
	}
	const delMember = (item, idx) => {
		console.log(item, idx);
		if (item.isSuperAdmin) return;
		if (!UserStore.CurrentSite) return;
		let _name = item.nickName || '匿名用户';
		proxy.$utils.alert('您确定要删除‘' + _name + '’吗？', function(bool) {
			if (bool) {
				let _mode = {
					id: item._id,
					site: UserStore.CurrentSite.path
				}
				console.log(_mode)
				loadData('P_Saas_RemoveUser', _mode, (res) => {
					console.log(res)
					try {
						if (res && res.status == '1') {
							proxy.$utils.msg(res.data1[0].tips);
							// --删除后更新成员数据
							proxy.$utils.timerout(() => {
								showRemove.value = false;
								onLoadData();
							}, 350)
							return;
						}
						proxy.$utils.msg("系统错误");
					} catch (e) {
						//TODO handle the exception
					}
				});
			}
		}, false);
	}

	const checkTeamMember = (item, index) => {
		console.log(item, index, modeType.value)
		switch (modeType.value) {
			case "radio":
				memberList.value.forEach((x, i) => {
					if (i == index) {
						memberList.value[i].checked = !memberList.value[i].checked
					} else {
						memberList.value[i].checked = false
					}
				})
				break;
			case "checkbox":
				memberList.value.forEach((x, i) => {
					if (i == index) {
						memberList.value[i].checked = !memberList.value[i].checked
					}
				})
				break;
			default:
				proxy.$utils.msg('未知操作');
				break;
		}
	}

	//   --选择负责人、成员完成
	const checkUserOver = () => {
		console.log(updateType.value)
		// --没有表单Id，只更新页面字段，不更新数据库
		let _checkList = [],
			_arr = [],
			_all = [];
		memberList.value.forEach((x) => {
			_all.push(x._id)
			if (x.checked) {
				_arr.push(x._id)
				_checkList.push(x);
			}
		})
		console.log(_checkList, _checkList.length == 0)
		if (_checkList.length == 0) {
			proxy.$utils.timerout(() => {
				closePopup('member')
			}, 250)
			return;
		}
		console.log(_checkList, superAdmin.value[0]);
		switch (updateType.value) {
			case 'head':
				console.log('超级管理员移交变更');
				/*
				参数说明：1->当前主管理员，2->被移交管理员
				*/
				proxy.$utils.alert('您确定要管理员权限移交给“ ' + _checkList[0].nickName + ' ”吗？', function(bool) {
					if (bool) {
						loadData('P_Saas_UserAuthOpera', {
							ids: superAdmin.value[0]._id,
							inherit: _checkList[0]._id,
							type: '1'
						}, (res) => {
							console.log(res)
							try {
								if (res && res.status == '1') {
									proxy.$utils.msg(res.data1[0].tips);
									proxy.$utils.timerout(() => {
										uni.switchTab({
											url: '/pages/tabbar/mine'
										});
									}, 2150)
									return;
								}
								proxy.$utils.msg("系统错误");
							} catch (e) {
								proxy.$utils.msg("系统错误");
							}
						});
					}
				});
				break;
			case 'admin':
				console.log('管理员权限变更');
				loadData('P_Saas_UserAuthOpera', {
					ids: _arr.join(','),
					inherit: '',
					type: '1'
				}, (res) => {
					console.log(res)
					try {
						if (res && res.status == '1') {
							proxy.$utils.msg(res.data1[0].tips);
							proxy.$utils.timerout(() => {
								onLoadData();
								showMemberPicker.value = false;
							}, 350)
							return;
						}
						proxy.$utils.msg("系统错误");
					} catch (e) {
						proxy.$utils.msg("系统错误");
					}
				});
				break;
			case 'member':

				break;
			default:
		}
	}
	const changeAdmin = () => {
		console.log(memberList.value, allMemberList.value);
		proxy.$utils.alert('您确定要变更管理员吗？', function(bool) {
			if (bool) {
				modeType.value = "radio";
				updateType.value = "head";
				const newList = allMemberList.value.filter(item => item.rid !== "625");
				console.log(newList);
				const _newList = newList.filter(item => item.rid !== "999");
				console.log(_newList);
				memberList.value = _newList;
				showMemberPicker.value = true;

			}
		});
	}
	const InviteMember = () => {
		console.log(UserStore.member, UserStore.CurrentSite, UserStore.CurrentSite.ORGID, UserStore.CurrentSite.path);
		let _ORGId = UserStore.CurrentSite.ORGID,
			_ORG = UserStore.CurrentSite.ORG,
			_site = UserStore.CurrentSite.path,
			_uid = UserStore.member.member_id,
			_inviter = UserStore.member.member_nickname;
		//_ORGId='d2cf8530-9b7f-4e83-8ecc-413102de698f',_ORG='聚友大道';
		let _path =
			`/pages/tabbar/launch?type=invite&source=&cId=${_ORGId}&mId=&title=${encodeURIComponent(_ORG)}&name=${encodeURIComponent(_inviter)}&uId=${_uid}&site=${_site}&mId=&timestamp=${Date.now()}`;
		console.log(_path);
		// #ifdef H5
		uni.navigateTo({
			url: _path
		});
		return;
		// #endif
		console.log("微信分享");
		uni.share({
			provider: 'weixin',
			scene: "WXSceneSession",
			type: 5,
			imageUrl: '',
			title: '欢迎体验聚管事',
			miniProgram: {
				id: proxy.$config.wxAppId,
				path: _path,
				type: 0,
				webUrl: ''
			},
			success: ret => {
				console.log(ret);
			},
			fail: function(err) {
				console.log("fail:" + JSON.stringify(err));
			}
		});
	}
	const openPopup = (state) => {}
	const closePopup = (type) => {
		switch (type) {
			case 'member':
				showMemberPicker.value = false
				break;
			case '':

				break;
			default:

		}
	}
	const onSearchClick = () => {

	}
	const messageToggle = (e, type) => {
		console.log(e)
		let _tips = e.target.dataset.tips;

		messageText.value = _tips;
		proxy.$refs.message.open();
	}
	// 超级管理员权限控制
	const permissions = () => {
		console.log(UserStore.member);
		if (UserStore.member.member_rid == '625') {
			hasPermissions.value = true;
		} else {
			hasPermissions.value = false;
		}
	}
	const toShare = () => {
		uni.share({
			provider: 'weixin',
			scene: "WXSceneSession",
			type: 5,
			imageUrl: '',
			title: '欢迎体验聚管事',
			miniProgram: {
				id: 'gh_abcdefg',
				path: 'pages/tabbar/launch',
				type: 0,
				webUrl: ''
			},
			success: ret => {
				console.log(JSON.stringify(ret));
			}
		});
	}
	// 加载成员列表
	const onLoadData = (type = 'add', loading) => {
		loadData('P_SaaS_FindUserbyFamily',{ type: 'family'}, (result) => {
			console.log("加载成员列表", result)
			if (result.status == '1') {
				let datas = [],
					_admins = [];
				if (result.data1 && result.data1.length > 0) {
					result.data1.forEach(x => {
						if (x.rid == '625') {
							_admins.push({
								_id: x.userid,
								avatarUrl: x.avatarurl,
								nickName: x.user_name
							})
						}
						if (x.rid != '999') {
							datas.push({
								_id: x.userid,
								avatarUrl: x.avatarurl,
								nickName: x.user_name,
								rid: x.rid,
								role: x.role,
								checked: false,
								isSuperAdmin: x.userid == lockingId.value ? true : false,
								locking: x.userid == lockingId.value ? true : false,
								tag: getType(x.rid)
							});
						}
					});
				} else {
					datas = [];
					_admin = {};
				}
				superAdmin.value = _admins; // 超级管理员				

				console.log("更新成员列表", datas)
				UserStore.putMemberList(datas);
				allMemberList.value = datas;
				// 使用 reduce 方法进行分组
				groupedData.value = datas.reduce((result, item) => {
					const group = item.tag;
					if (!result[group]) {
						result[group] = [];
					}
					result[group].push(item);
					return result;
				}, {});
				// 分组后的结果
				console.log("分组后的结果", groupedData);
				setTimeout(() => {
					teacherList.value = groupedData.value.admins || [];
					memberList.value = groupedData.value.members || [];
					// NonStaffList.value = groupedData.value.NonStaff;
					if (checkedList.value.length > 0) {
						checkedList.value.forEach((x) => {
							memberList.value.forEach((y, i) => {
								if (x == y._id) {
									memberList.value[i].checked = true
								}
							})
							// NonStaffList.value.forEach((k, j) => {
							// 	if (x == k._id) {
							// 		NonStaffList.value[j].checked = true
							// 	}
							// })
						})
					}
				}, 150)
			}
		});
	}
	const getType = (type) => {
		// case '625':			return 'MainAdmin'			break;
		// case '626':			return 'SubAdmin'			break;
		// case '803':			return 'Members'			break;
		let _bool = false;
		if (type == '625' || type == '626') {
			_bool = true;
		}
		switch (_bool) {
			case true:
				return 'admins'
				break;
			default:
				return 'members'
		}
	}
	const loadData = async (type, mode, callback) => {
		let param, _param, _res, __res;
		switch (type) {
			case 'P_Saas_UserAuthOpera':
				param = {
					storedPro: 'P_Saas_UserAuthOpera',
					paraNum: 3,
					resultSetNum: 1,
					para1: mode.ids,
					para2: mode.inherit,
					para3: mode.type
				}
				console.log(param);
				_res = await getData(param);
				break;

			case 'P_Saas_RemoveUser': // --移除成员
				/*				 
				 */
				param = {
					storedPro: 'P_Saas_RemoveUser',
					paraNum: 2,
					resultSetNum: 1,
					para1: mode.id,
					para2: mode.site
				}
				_res = await getData(param);
				break;
			case 'P_SaaS_FindUserbyFamily':
				param = {
					storedPro: 'P_SaaS_FindUserbyFamily',
					paraNum: 3,
					resultSetNum: 1,
					
					para1: UserStore.member.member_id,
					para2:UserStore.member.family_id,
					para3: 'family'
				}
				_res = await getData(param);
				break;
			default:
		}
		if (typeof callback === 'function') {
			// 数据加载完成回调函数
			callback(_res);
		}
	}

	const getData = (param) => {
		console.log(param)
		let url = proxy.$config.baseUrl;
		let params = {
			loading: false,
			url: '/webapi/eidData.ashx?oper=LTTG_Multifunction',
			method: 'get',
			data: param
		}
		return new Promise((resolve, reject) => {
			proxy.$api.getData(url, params).then((res) => {
				// console.log(res);
				if (res.status == '1') {
					resolve(res);
				} else {
					reject('获取信息失败' + res.msg)
				}
			})
		})
	}
	// 计算属性
	const totalNum = computed({
		get() {
			return memberList.value.filter(item => item.checked).length + NonStaffList.value.filter(item =>
				item.checked).length
		},
		set(value) {}
	})

	onMounted(() => {

	})

	//-- 微信分享实际操作

	let shareImg = proxy.$config.shareImage;
	onShareAppMessage((res) => {
		console.log(res)
		console.log(UserStore.member, UserStore.CurrentSite, UserStore.CurrentSite.ORGID, UserStore.CurrentSite
			.path);
		let _ORGId = UserStore.CurrentSite.ORGID,
			_ORG = UserStore.CurrentSite.ORG,
			_site = UserStore.CurrentSite.path,
			_uid = UserStore.member.member_id,
			_inviter = UserStore.member.member_nickname;
		//_ORGId='d2cf8530-9b7f-4e83-8ecc-413102de698f',_ORG='聚友大道';
		let _path =
			`/pages/tabbar/launch?type=invite&source=join&cId=${_ORGId}&mId=&title=${encodeURIComponent(_ORG)}&name=${encodeURIComponent(_inviter)}&uId=${_uid}&site=${_site}&timestamp=${Date.now()}`;
		console.log(_path);
		if (res.from === 'button') {
			// 来自页面内分享按
			return {
				title: `"${UserStore.member.member_nickname}"邀请您加入"${UserStore.CurrentSite.ORG}"`,
				path: _path,
				imageUrl: shareImg,
				success: function(res) {
					// 转发成功
					proxy.$utils.msg('转发成功~');
				},
				fail: function(res) {
					// 转发失败
					proxy.$utils.msg('转发失败~');
				}
			};
		} else {
			return {
				title: `"${UserStore.member.member_nickname}"邀请您加入"${UserStore.CurrentSite.ORG}"`,
				path: _path,
				imageUrl: shareImg,
				success: res => {
					proxy.$utils.msg('转发成功~');
				},
				fail: err => {
					proxy.$utils.msg('转发失败~');
				}
			};
		}
	})
	onShareTimeline(() => {
		return {
			title: '雅歌洗化，不辜负每一份热爱',
			query: 'share=', // 可不填 传递的参数，只能是这种格式
			imageUrl: urlImg
		}
	})
</script>

<style lang="scss">
	page,
	.page-container {
		background-color: $uni-bg-color-grey;
		min-height: 100vh;
	}

	.search-area {

		input {
			padding-left: 80rpx;
			height: 76rpx;
			line-height: 76rpx;
		}

		.icon-search {
			top: 50%;
			left: 30rpx;
			transform: translate(0, -50%);
			z-index: 1;

			text {
				color: #c0c0c0;
			}
		}
	}

	.oper-area {
		z-index: 98;
		box-shadow: 0 -1px 5px rgba(0, 0, 0, 0.1);
		height: 100rpx;
		height: calc(env(safe-area-inset-bottom) + 100upx);

		.submit {
			height: 66rpx;
		}
	}
	
	.headimg.big {
		width: 65px;
		height: 65px;
		background-color: #f5f5f5;
	
		.avatar {
			max-width: 100%;
			height: 100%;
		}
	}
</style>